package com.haut.servlet;

import com.alibaba.fastjson.JSON;
import com.haut.bean.Position;
import com.haut.service.PositionService;
import com.haut.service.impl.PositionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet({"/position/add","/position/delete","/position/name"})
public class PositionServlet extends HttpServlet{
    PositionService positionService=new PositionServiceImpl();

    protected void service (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String servletPath = request.getServletPath();
        if("/position/add".equals(servletPath)){
            doAdd(request,response);
        }else if("/position/delete".equals(servletPath)){
            doDelet(request,response);
        }else if("/position/name".equals(servletPath)){
            doName(request,response);
        }
    }

    private void doAdd(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        String dept=request.getParameter("dept");
        positionService.add(new Position(0,name,dept));
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("add");
    }

    private void doDelet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        String dept=request.getParameter("dept");
        positionService.delete(new Position(0,name,dept));
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("delete");
    }

    private void doName(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String dept_name=request.getParameter("dept");
        String json= JSON.toJSONString(positionService.getPositionName(dept_name));
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
    }

}
